(function ($) {
    $.fn.ycmfBatchView = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.yiiGridView');
            return false;
        }
    };

    var defaults = {
        filterUrl: undefined
    };

    var batchData = {};

    var batchEvents = {
        beforeBatch: 'beforeBatch',
        afterBatch: 'afterBatch'
    };
    
    var methods = {
        init: function (options) {
            return this.each(function () {
                var $e = $(this);
                var settings = $.extend({}, defaults, options || {});
                var $grid = $('#' + settings.gridId),
                    checkboxName =  settings.checkboxName;

                batchData[$e.prop('id')] = {settings: settings};

                $(document).off('click.ycmfBatch', '#' + $e.prop('id') + ' :submit')
                    .on('click.ycmfBatch', '#' + $e.prop('id') + ' :submit', function (event) {
                        methods.applyBatch.apply($e);
                        return false;
                    });
                $(document).off('click.ycmfBatch', '#' + $grid.prop('id') + ' input[type=checkbox]:enabled').
                    on('click.ycmfBatch', '#' + $grid.prop('id') + ' input[type=checkbox]:enabled', function() {
                        setTimeout(function() {
                            $e.find(':submit').prop('disabled', !$('#' + $grid.prop('id') + ' input[name="' + checkboxName + '"]:checked').length);
                        }, 0);
                    })
            });
        },

        applyBatch: function () {
            var $batch = $(this), event;
            var settings = batchData[$batch.prop('id')].settings;
            var $grid = $('#' + settings.gridId);
            var data = {};

            $.each($(settings.batchSelector), function () {
                data[this.name] = this.value;
            });

            var url = settings.batchUrl;

            $batch.find('form.batch-form').remove();
            var $form = $('<form action="' + url + '" method="post" class="batch-form" style="display:none" data-pjax></form>').appendTo($batch);
            $.each(data, function (name, value) {
                $form.append($('<input type="hidden" name="t" value="" />').attr('name', name).val(value));
            });

            $.each($grid.find('input[name="' + settings.checkboxName + '"]:checked'), function() {
                $form.append($('<input type="hidden" name="t" value="" />').attr('name', this.name).val(this.value));
            });

            event = $.Event(batchEvents.beforeBatch);
            $batch.trigger(event);
            if (event.result === false) {
                return;
            }

            $form.submit();
            
            $batch.trigger(batchEvents.afterBatch);
        },

        setConfirmColumn: function(name, confirm)
        {
            var $batch = $(this);

            $batch.on(batchEvents.beforeBatch, function(e) {
                $.each(confirm, function(value, message) {
                    if ($batch.find('[name="' + name + '"]').val() == value) {
                        if (!window.confirm(message)) {
                            e.result = false;
                            return false;
                        }
                    }
                })
            });
        },

        destroy: function () {
            return this.each(function () {
                $(window).unbind('.ycmfBatchView');
                $(this).removeData('ycmfBatchView');
            });
        },

        data: function () {
            var id = $(this).prop('id');
            return batchData[id];
        }
    };
})(window.jQuery);
